package com.yuntoyun.codeavatar.app.activity.main;

import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.flyco.tablayout.SlidingTabLayout;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.yuntoyun.codeavatar.app.R;
import com.yuntoyun.codeavatar.app.activity.basic.LoginActivity;
import com.yuntoyun.codeavatar.app.activity.ext.HomeBannerHolder;
import com.yuntoyun.codeavatar.app.fwcore.activity.WebPageActivity;
import com.yuntoyun.codeavatar.app.fwcore.core.AppCoreSign;
import com.yuntoyun.fwcore.adapter.FwFragmentPagerAdapter;
import com.yuntoyun.fwcore.base.FwBaseFragment;
import com.yuntoyun.fwcore.model.FwResultJsonDataModel;
import com.yuntoyun.fwcore.model.FwResultJsonListDataModel;
import com.yuntoyun.fwcore.plug.network.retrofit.FwOkHttp;
import com.yuntoyun.fwcore.plug.tool.FwNavigationTool;
import com.yuntoyun.fwcore.plug.tool.model.FwNavigationModel;
import com.yuntoyun.fwcore.tool.login.LoginTool;
import com.yuntoyun.fwcore.util.FwIntentUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;

public class TaskFragment extends FwBaseFragment {

    private final String fTag = TaskFragment.class.getSimpleName();

    private final int gActionLoad = 901;

    @BindView(R.id.cbr_banner)
    ConvenientBanner cbr_banner;
    @BindView(R.id.stl_tabs)
    SlidingTabLayout stl_tabs;
    @BindView(R.id.vpr_pages)
    ViewPager vpr_pages;

    private List<Fragment> gTabFragments = new ArrayList<>();
    private List<String> gTabNames = new ArrayList<>();

    @Override
    protected boolean isAgainCreateView() {
        return false;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_main_task;
    }

    @Override
    protected void initView(View layoutView) {
        FwNavigationModel model = FwNavigationTool.getHeadBarModel(layoutView);
        model.getTvwCenterTitle().setText("任务");
        TextView tvwRightAction = model.getTvwRightAction();
        tvwRightAction.setText("我的任务");
        tvwRightAction.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (LoginTool.isLogin(getActivity(), LoginActivity.class)) {
//                    FwIntentUtil.builder().startActivity(getActivity(), TaskListActivity.class);
                }
            }
        });
    }

    @Override
    protected void initData() {
        this.doLoadData();
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void initNavigation() {

    }

    @Override
    protected void messageHandler(Message msg) {

    }

    @Override
    protected void messageHandler(FwResultJsonDataModel model) {
        switch (model.getIndex()) {
            case gActionLoad:
                JsonArray jarrBanner = fwGsonUtil.getJsonArray(model.getFwData(), "banner");
                initBannerView(jarrBanner);
                JsonArray jarrTab = fwGsonUtil.getJsonArray(model.getFwData(), "taskCate");
                initTabsView(jarrTab);
                break;
        }
    }

    @Override
    protected void messageHandler(FwResultJsonListDataModel model) {

    }

    @Override
    public void onClick(View v) {

    }

    //=================================================================================

    public void reloadData() {
        for (Fragment fragment : gTabFragments) {
            if (fragment instanceof TaskTabOtherFragment) {
                TaskTabOtherFragment fragment1 = (TaskTabOtherFragment) fragment;
                fragment1.doRefreshData(true);
            } else if (fragment instanceof TaskTabVideoFragment) {
                TaskTabVideoFragment fragment2 = (TaskTabVideoFragment) fragment;
                fragment2.reloadData();
            }
        }
    }


    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    private void doLoadData() {
        HashMap<String, Object> map = new HashMap<>();
        AppCoreSign.addSign(map);
        Observable<FwResultJsonDataModel> observable = FwOkHttp.getFwAPIService().getTaskInfo(map);
        super.doPostData(this.gActionLoad, observable, true);
    }

    //布局BannerView
    private void initBannerView(JsonArray jarr) {
//        int pPageIndicator[] = new int[]{R.mipmap.icon_indicator_default, R.mipmap.icon_indicator_checked};
        int pPageIndicator[] = new int[]{R.drawable.style_task_banner_indiator_default, R.drawable.style_task_banner_indiator_checked};

        List<JsonObject> pBannerList = new ArrayList<>();
        for (int i = 0; i < jarr.size(); i++) {
            pBannerList.add(fwGsonUtil.getJsonObject(jarr, i));
        }
        cbr_banner.setPages(new CBViewHolderCreator() {
            @Override
            public Holder createHolder(View itemView) {
                return new HomeBannerHolder(fwActivity, itemView);
            }

            @Override
            public int getLayoutId() {
                return R.layout.fw_plug_banner_img;
            }
        }, pBannerList).setPageIndicator(pPageIndicator).setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                JsonObject joItem = pBannerList.get(position);
                if (null == joItem) return;

                if (joItem.has("is_jump")) {
                    //是否跳转：0 不跳；1 跳转；
                    if (1 == fwGsonUtil.getInt(joItem, "is_jump")) {
                        Bundle extra = new Bundle();
                        extra.putString("ext_title", "详情");
                        extra.putString("ext_url", fwGsonUtil.getString(joItem, "url"));
                        FwIntentUtil.builder().startActivity(fwActivity, WebPageActivity.class, extra);
                    }
                }
            }
        });

        if (pBannerList.size() > 1) {
            cbr_banner.startTurning(5000);
        }
    }

    //布局TabsView
    private void initTabsView(JsonArray jarrTab) {
        //清除数据
        gTabNames.clear();
        gTabFragments.clear();

        //任务类型：0 其他任务；1 视频任务
        for (JsonElement element : jarrTab) {
            gTabNames.add(fwGsonUtil.getString(element.getAsJsonObject(), "title"));
            if (0 == fwGsonUtil.getInt(element.getAsJsonObject(), "task_type")) {
                gTabFragments.add(new TaskTabOtherFragment());
            } else if (1 == fwGsonUtil.getInt(element.getAsJsonObject(), "task_type")) {
                TaskTabVideoFragment tabVideoFragment = new TaskTabVideoFragment();
                tabVideoFragment.setJarrTags(fwGsonUtil.getJsonArray(element.getAsJsonObject(), "taskPlatform"));
                gTabFragments.add(tabVideoFragment);
            }
        }
        //ViewPager 未嵌套使用 getFragmentManager()，嵌套使用 getChildFragmentManager()。(否则不加载界面)
        FwFragmentPagerAdapter fwPagerAdapter = new FwFragmentPagerAdapter(getChildFragmentManager(), gTabFragments, gTabNames);
        vpr_pages.setAdapter(fwPagerAdapter);
        stl_tabs.setViewPager(vpr_pages);
    }

}
